package com.threadpool.pool.policy;

import com.threadpool.pool.CustomThreadPool;
import com.threadpool.pool.queue.CustomBlockingQueue;

/**
 * <p>
 * 抛弃旧任务策略
 * </p>
 *
 * @author 桌角的眼镜
 * @version 1.0
 * @since 2025/5/14 0:50
 */
public class DiscardOldestPolicy<T> implements RejectPolicy<T> {
    @Override
    public void reject(T task, CustomThreadPool pool) {
        CustomBlockingQueue<T> queue = (CustomBlockingQueue<T>) pool.getTaskQueue();

        // 丢弃队列头部任务（非阻塞）
        T oldest = queue.poll();
        if (oldest != null) {
            if (!queue.offer(task)) {
                throw new RuntimeException("即使丢弃了最旧的任务，任务仍被拒绝");
            }
        } else {
            throw new RuntimeException("任务被拒绝：队列空，没有东西可以丢弃");
        }
    }
}

